﻿// Program.fs
//
// Copyright 2009 Sergey Mechtaev
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation.


#light

namespace SmartCPP.ConsoleApp

open SmartCPP.Core.Preprocessor
open SmartCPP.Core.Util
open System.IO
open System.Text

module Main = 
  let main () =         
      let console_args = System.Environment.GetCommandLineArgs()
      let input_file = console_args.[1]
      let output_file = console_args.[2]
         
      
      use inputReader = File.OpenText(input_file)
      let fileContentString = (inputReader.ReadToEnd() + "\n" )
      let fileContent = fileContentString.ToCharArray();
      
         
         
      let input_lines = List.map (fun s -> 1 + String.length s) (String.split ['\n'] fileContentString)    
      let segToLac = Binding.segToLineAndColumn input_lines
      
      
      
      printf "processing... "
      let new_text, history = Preprocessor.start fileContent input_file
      printfn "OK"
      
      let output_lines = List.map (fun s -> 1 + String.length s) (String.split ['\n'] new_text)
      let lacToSeg = Binding.lineAndColumnToSeg output_lines   
     
      printf "printing output... "
      use output = File.CreateText(output_file)
      output.Write new_text
      output.Close()
      printfn "OK"
      
      printf "printing history... "    
      use historyOutput = File.CreateText(output_file+".history")
      historyOutput.Write (Printing.print_history history)
      historyOutput.Close()
      printfn "OK"
      
      if console_args.Length > 3 then
          let segment = lacToSeg ((int console_args.[3], int console_args.[4]), (int console_args.[5], int console_args.[6]))
          printfn ""
          printf "%A" (new_text.Substring(fst segment, snd segment))
          printfn ""
          printfn "----Preimage----"
          Printing.print_preimage (Binding.preimage segment history) segToLac
          printfn ""
      
      
      printfn "complete"
      //Use CTRL+F5 to run with console window from MSVS    System.Console.In.Read() |> ignore
      
  do main()     